from django.shortcuts import render, redirect
from user_operations.models import Comments
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse
from django.contrib.auth import get_user_model
User = get_user_model()


# Create your views here.


def comment(request):
    """
    接收评论，并入库
    1、评论的用户
    2、评论的电影
    3、评论的内容
    :param request:
    :return:
    """
    # url_source = request.META['HTTP_REFERER']
    # # ⬇ 取出评论的数据
    # comment_data = dict()
    # # ⬇ POST是dict,POST['comic'],如果没有 comic 这个key,会报错
    # # ⬇ 使用 .get 就可以获取 comic，如果没有就默认返回 None
    # comic_id = request.POST.get('comic', None)
    # content = request.POST.get('content', None)
    #
    # # ⬇ 添加数据
    # comment_data['user'] = request.user.id
    # comment_data['content'] = content
    # comment_data['comic'] = comic_id
    #
    # # ⬇ 验证,数据不合法就返回原页面
    # data = CommentValiForm(comment_data)
    #
    # if not data.is_valid():
    #     return redirect(url_source)
    # data.save()
    # return redirect(url_source)
    url_source = request.META['HTTP_REFERER']

    user_id = request.user.id
    comic_id = request.POST.get('comic', None)
    content = request.POST.get('content', None)

    comment_data = Comments()

    if all([user_id, comic_id, content]):
        user_id = int(user_id)
        comment_data.user_id = user_id
        comment_data.comic_id = comic_id
        comment_data.content = content

        comment_data.save()

        comments = Comments.objects.filter(comic=comic_id)
        return redirect(url_source)

    else:
        return redirect(url_source)

















